<?php

class RankingController extends \Phalcon\Mvc\Controller
{	

	private function sortBy($for_display,$type){
		switch($type)
		{
			case "ranking":

				for ($y=0; $y < sizeof($for_display) - 1 ; $y++) { 
					for ($i=$y; $i < sizeof($for_display) - 1; $i++) { 
					
						if($for_display[$i]['points'] < $for_display[$i + 1]['points'])
						{
							$temp = $for_display[$i];
							$for_display[$i] = $for_display[$i + 1];
							$for_display[$i + 1] = $temp;	
						}

					}		# code...

				}

				$ranking = 1;
				for ($i=0; $i <=  sizeof($for_display) - 1 ; $i++) { 
					if($for_display[$i]['points'] > $for_display[$i + 1]['points'])
					{
						$for_display[$i]['ranking'] = $ranking;
						$ranking += 1;
					}
					else if($for_display[$i]['points'] == $for_display[$i + 1]['points']){
						$for_display[$i]['ranking'] = $ranking;
					}else{
						$for_display[$i]['ranking'] = $ranking;
					}
				}
			
			break;
		}

		return $for_display;

	}

    public function indexAction()
    {
		$this->view->setMainView('index');
		$this->view->setVar('page_name', 'Ranking');
		$this->view->setVar('content', 'ranking/index');
		$this->view->setVar('title', 'Ranking');

		$companies = ClientInfo::find();

		$result = array();

		$categories = array();
		$reviews_followers = array();
		$views = array();
		$for_display = array();
		

		foreach ($companies as $value) {
			$reviews =  ceil(CompanyRatings::getAvg($value->id));
			$followers = CompanyFollowers::listTotalFollowers($value->id);
			
			$categories[] = $value->name;
			$reviews_followers[] = $followers + $reviews;
			$views[] = CompanyVisitors::listVisitorsById($value->id);	

			$quarter = CompanyVisitors::listVisitorsQuarterly($value->id);
			$quarterly = array();
			foreach ($quarter as $value2) {
				$quarterly[] = $value2->total_visitors;
			}

			$for_display[] = array(
				 "name"=>$value->name,
				 "location"=>$value->location,
				 "followers"=>$followers,
				 "views_quarterly" => $quarterly,
				 "reviews"=>$reviews,
				 "points"=> (.7 * $reviews) + (.3 * $followers),
				 "href"=>"",
				 "company_id"=>$value->id,
				 "quarterly"=>implode(",", $quarterly)
 				);
		}
		$result = array(
				"categories"=>$categories,
				"reviews_followers"=>$reviews_followers,
				"visitors"=>$views
			);

		// bubble sort
		
		$for_display = $this->sortBy($for_display,"ranking");
		

		$this->view->setVar('for_display',$for_display);
		$this->view->setVar('analytics_json',json_encode($result));
		
    }

}

